<template>
  <el-dialog
    class="modify-dialog"
    title="绑定手机号"
    :visible.sync="dialogVisible"
    width="35%"
    :before-close="handleCancel"
    append-to-body>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="ruleForm.phone" type="text" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item style="text-align: right;">
        <el-button :loading="loading" type="primary" @click="submitForm('ruleForm')">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { changeCurrentInfo } from '../../../api/system/person/api'
import { mapState, mapActions } from "vuex";
export default {
  data () {
    return {
      dialogVisible: false,
      ruleForm: {
        phone: ''
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    ...mapActions("user", ["LogOut"]),
    // 显示
    show()
    {
      this.dialogVisible = true
    },
    // 添加
    submitForm(formName)
    {
      this.$refs[formName].validate((valid) => {
        if (valid) 
        {
          this.loading = true;
          changeCurrentInfo({
            phonenumber: this.ruleForm.phone
          }).then(res => {
            this.loading = false
            this.$message.success("修改成功");
            this.$emit('login')
          })
        } 
        else 
        {
          this.loading = false;
          return false;
        }
      });
    },
    // 取消
    handleCancel()
    {
      this.$refs.ruleForm.resetFields();
      this.dialogVisible = false
      //移除token
      this.LogOut();
    },
    handleBeforeUnload()
    {
      console.log("-----触发销毁---------")
      if (this.dialogVisible)
      {
        //移除token
        this.LogOut();
      }
    }
  },
  mounted() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  beforeDestroy()
  {
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  }
}
</script>

<style scoped>
.modify-dialog {
  top: 50%;
  transform: translateY(-50%);
  margin-top: 0 !important;
}
</style>